import { CheckAns } from "./CheckAns";

namespace LeetCode0703KthLargest {

    class KthLargest {
        // 定制有序容器（从大到小排序）
        private myVactor: number[] = new Array();
        // 容器限制大小
        private limitSize: number = 0;

        // 需求规定需要实现的初始化函数
        constructor(k: number, nums: number[]) {
            if (k < 0) return this;
            // 保存K，并处理数组
            this.limitSize = k;
            const len: number = nums ? nums.length : 0;
            const initEnd: number = Math.min(k, len);
            if (initEnd > 0)
                this.myVactor = nums.slice(0, initEnd).sort((a: number, b: number) => { return b - a; });
            // TODO LOG
            console.log("init subArray ", JSON.stringify(this.myVactor));
            // add if there has some numbers
            if (len > k) {
                for (let i = k; i < len; i++) {
                    this.add(nums[i]);
                }
            }
            // TODO LOG
            console.log("end init~~~");
            return this;
        }

        // 需求规定需要实现的方法
        add(val: number): number {
            if (this.limitSize < 0)
                return 0;
            // 查找排序插入位置
            const idx: number = this.myVactor.findIndex((v: number) => { return v <= val; });
            // 仅插入有效值
            if (idx >= 0 && idx < this.limitSize)
                this.myVactor.splice(idx, 0, val);
            else if (idx == -1 && this.myVactor.length < this.limitSize) {
                // 特殊处理初始化不满足的情况
                this.myVactor.push(val);
            }
            // 维护数组长度
            if (this.myVactor.length > this.limitSize)
                this.myVactor.splice(this.limitSize);
            // TODO LOG
            console.log("add func ", JSON.stringify(this.myVactor));
            return this.myVactor[this.limitSize - 1] || 0;
        }
    }

    // test
    const testData: { k: number, inits: number[], inputs: number[], ans: number[] }[] = [
        { k: 7, inits: [-10, 1, 3, 1, 4, 10, 3, 9, 4, 5, 1], inputs: [3, 2, 3, 1, 2, 4, 5, 5, 6, 7, 7, 8, 2, 3, 1, 1, 1, 10, 11, 5, 6, 2, 4, 7, 8, 5, 6], ans: [3, 3, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7] },
        { k: 3, inits: [4, 5, 8, 2], inputs: [3, 5, 10, 9, 4], ans: [4, 5, 5, 8, 8] },
        { k: 1, inits: [], inputs: [-3, -2, -4, 0, 4], ans: [-3, -2, -2, 0, 4] }
    ];
    for (const data of testData) {
        const obj = new KthLargest(data.k, data.inits);
        if (!obj) continue;
        let ans: number[] = new Array();
        for (const val of data.inputs) {
            ans.push(obj.add(val));
        }
        CheckAns(data, ans);
    }
}
